package com.gitee.secretopen.sso.controller;


import cn.chenc.framework.core.model.request.RequestHolder;
import cn.chenc.framework.core.model.response.ResponseVO;
import cn.chenc.framework.core.model.response.ResultUtil;
import cn.chenc.framework.excel.util.EasyExcelUtil;
import com.gitee.secretopen.sso.controller.form.PageInfo;
import com.gitee.secretopen.sso.db.pojo.Log;
import com.gitee.secretopen.sso.excelmodel.LogUpload;
import com.gitee.secretopen.sso.service.LogService;
import com.google.common.primitives.Ints;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 日志表 前端控制器
 * </p>
 *
 * @author secret
 * @since 2021-02-25
 */
@RestController
@RequestMapping("/admin")
public class LogController {
    @Autowired
    private LogService logService;

    @GetMapping("/log/{id}")
    public ResponseVO<Log> getOne(@PathVariable("id") int id) {
        Log log = logService.getById(id);
        return ResultUtil.success(log);
    }

    @PostMapping("/logs")
    public ResponseVO<PageInfo<Log>> list(@RequestBody Log params){
        PageInfo<Log> page = logService.page(params);
        return ResultUtil.success(page);
    }

    @PostMapping("/log")
    public ResponseVO save(@RequestBody Log log){
        logService.save(log);
        return ResultUtil.success("新增成功！");
    }

    @PutMapping("/log")
    public ResponseVO update(@RequestBody Log log) {
        logService.updateById(log);
        return ResultUtil.success("更新成功！");
    }

    @DeleteMapping("/log/{id}")
    public ResponseVO delete(@PathVariable("id") int id) {
        logService.removeById(id);
        return ResultUtil.success("删除成功");
    }

    @DeleteMapping("/logs")
    public ResponseVO deleteMulti(@RequestBody int[] ids) {
        List<Integer> id = Ints.asList(ids);
        logService.removeByIds(id);
        return ResultUtil.success("删除成功");
    }

    @ResponseBody
    @PostMapping(value = "/logs/download")
    public void downloadLogs() {
        List<Log> logList = logService.downloadLogs();
        HttpServletResponse response = RequestHolder.getResponse();
        EasyExcelUtil.toExcle(response, logList, "secret_sso_日志清单", LogUpload.class);
    }

    @GetMapping("/logAdd")
    public ResponseVO insert() {
        Log log = new Log();
        log.setInfo("xxx登录系统");
        log.setIp("0.0.0.0");
        log.setCreateTime(LocalDateTime.now());
        boolean re = logService.save(log);
        if (re) {
            return ResultUtil.success("log add success!");
        }
        return ResultUtil.error("log add error");
    }

}

